package network.okhttp.http7_1;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * 输入淘宝地址http://www.taobao.com
 * 爬取内容
 * 打印结果
 */
public class GetPage {
    private OkHttpClient okHttpClient;

    public GetPage(){
        okHttpClient = new OkHttpClient();
    }

    public String getPageContentSync(String url){
        // 参数判断，未输入参数则直接返回
        if (StringUtils.isBlank(url)){
            return null;
        }
        //2.定义一个request
        Request request = new Request.Builder().url(url).build();
        //3.使用client去请求
        Call call = okHttpClient.newCall(request);
        String result = null;
        try {
            //4.获得返回结果
            result = call.execute().body().string();
            System.out.println("call " + url +", content's size "+result.length());
        } catch (IOException e) {
            System.out.println("request " +url +" error ");
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println( new GetPage().getPageContentSync("http://www.taobao.com"));

    }

}
